###################
# Load packages and Libraries
###################

library(dplyr)
library(tidyverse)
library(haven)
library(foreign)

# Clear All
rm(list = ls())

gerrymander_r <- read_dta("irca_gerrymander.dta")

#Keep certain variables
gerrymander_r = gerrymander_r[c("irca_apps_pc_impute","id", "year")]
gerrymander_r = filter(gerrymander_r, year == 1990)

##############
## Load Map Data
##############
# Load Counties Data
maps::county.fips %>%
  as.tibble %>% 
  extract(polyname, c("region", "subregion"), "^([^,]+),([^,]+)$") ->
  dfips

# Merge to County longitude and latitude
map_data("county") %>% 
  left_join(dfips) ->
  dall

#plot Counties only
ggplot(data=dall) + 
  geom_polygon(aes(x=long, y=lat, group=group), colour="black", fill='white', size=.2) +
  coord_fixed(1.3) + theme_void()

#Merge IRCA data to county FIPS data
irca_data <- full_join(dall, gerrymander_r, by=c("fips"="id"))

##############
## Plot
##############

#Plot data into deciles
irca_data_decile <- mutate(irca_data, irca_decile = ntile(irca_apps_pc_impute, 10))

#Deciles plot with different label: continuous but spectral
pdf("fig2.pdf") 
par(mar = c(0, 2, 0, 2))  # Adjust margins as needed
ggplot(data = irca_data_decile) +
  geom_polygon(aes(x=long, y=lat, group=group, fill=irca_decile), colour="black", size=.1) +
  theme_void() + coord_fixed(1.2) +
  scale_fill_distiller(palette = "Spectral", name="", trans="reverse",
                       breaks=c(1,5,10),
                       labels=c("1", "5", "10")) +
  ggtitle("IRCA Migrants per 100,000 Population (by Decile)") +
  theme(legend.position = c(.5, 0), legend.direction = "horizontal", legend.title = element_text(size=7), legend.text = element_text(size=7),
        plot.title = element_text(size=15, face="bold.italic", hjust=.5)) 
dev.off()